package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Account;
import cn.ibizlab.businesscentral.core.base.service.IAccountService;
import cn.ibizlab.businesscentral.core.base.filter.AccountSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"客户" })
@RestController("CentralApi-account")
@RequestMapping("")
public class AccountResource {

    @Autowired
    public IAccountService accountService;

    @Autowired
    @Lazy
    public AccountMapping accountMapping;

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdto),'iBizBusinessCentral-Account-Create')")
    @ApiOperation(value = "新建客户", tags = {"客户" },  notes = "新建客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts")
    @Transactional
    public ResponseEntity<AccountDTO> create(@RequestBody AccountDTO accountdto) {
        Account domain = accountMapping.toDomain(accountdto);
		accountService.create(domain);
        AccountDTO dto = accountMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdtos),'iBizBusinessCentral-Account-Create')")
    @ApiOperation(value = "批量新建客户", tags = {"客户" },  notes = "批量新建客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.createBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "account" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.accountService.get(#account_id),'iBizBusinessCentral-Account-Update')")
    @ApiOperation(value = "更新客户", tags = {"客户" },  notes = "更新客户")
	@RequestMapping(method = RequestMethod.PUT, value = "/accounts/{account_id}")
    @Transactional
    public ResponseEntity<AccountDTO> update(@PathVariable("account_id") String account_id, @RequestBody AccountDTO accountdto) {
		Account domain  = accountMapping.toDomain(accountdto);
        domain .setAccountid(account_id);
		accountService.update(domain );
		AccountDTO dto = accountMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.accountService.getAccountByEntities(this.accountMapping.toDomain(#accountdtos)),'iBizBusinessCentral-Account-Update')")
    @ApiOperation(value = "批量更新客户", tags = {"客户" },  notes = "批量更新客户")
	@RequestMapping(method = RequestMethod.PUT, value = "/accounts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.updateBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.accountService.get(#account_id),'iBizBusinessCentral-Account-Remove')")
    @ApiOperation(value = "删除客户", tags = {"客户" },  notes = "删除客户")
	@RequestMapping(method = RequestMethod.DELETE, value = "/accounts/{account_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("account_id") String account_id) {
         return ResponseEntity.status(HttpStatus.OK).body(accountService.remove(account_id));
    }

    @PreAuthorize("hasPermission(this.accountService.getAccountByIds(#ids),'iBizBusinessCentral-Account-Remove')")
    @ApiOperation(value = "批量删除客户", tags = {"客户" },  notes = "批量删除客户")
	@RequestMapping(method = RequestMethod.DELETE, value = "/accounts/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        accountService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.accountMapping.toDomain(returnObject.body),'iBizBusinessCentral-Account-Get')")
    @ApiOperation(value = "获取客户", tags = {"客户" },  notes = "获取客户")
	@RequestMapping(method = RequestMethod.GET, value = "/accounts/{account_id}")
    public ResponseEntity<AccountDTO> get(@PathVariable("account_id") String account_id) {
        Account domain = accountService.get(account_id);
        AccountDTO dto = accountMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取客户草稿", tags = {"客户" },  notes = "获取客户草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/accounts/getdraft")
    public ResponseEntity<AccountDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(accountMapping.toDto(accountService.getDraft(new Account())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-Active-all')")
    @ApiOperation(value = "激活", tags = {"客户" },  notes = "激活")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/{account_id}/active")
    @Transactional
    public ResponseEntity<AccountDTO> active(@PathVariable("account_id") String account_id, @RequestBody AccountDTO accountdto) {
        Account domain = accountMapping.toDomain(accountdto);
domain.setAccountid(account_id);
        domain = accountService.active(domain);
        accountdto = accountMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(accountdto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-AddList-all')")
    @ApiOperation(value = "添加到市场营销列表", tags = {"客户" },  notes = "添加到市场营销列表")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/{account_id}/addlist")
    @Transactional
    public ResponseEntity<AccountDTO> addList(@PathVariable("account_id") String account_id, @RequestBody AccountDTO accountdto) {
        Account domain = accountMapping.toDomain(accountdto);
domain.setAccountid(account_id);
        domain = accountService.addList(domain);
        accountdto = accountMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(accountdto);
    }

    @ApiOperation(value = "检查客户", tags = {"客户" },  notes = "检查客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody AccountDTO accountdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(accountService.checkKey(accountMapping.toDomain(accountdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-Inactive-all')")
    @ApiOperation(value = "停用", tags = {"客户" },  notes = "停用")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/{account_id}/inactive")
    @Transactional
    public ResponseEntity<AccountDTO> inactive(@PathVariable("account_id") String account_id, @RequestBody AccountDTO accountdto) {
        Account domain = accountMapping.toDomain(accountdto);
domain.setAccountid(account_id);
        domain = accountService.inactive(domain);
        accountdto = accountMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(accountdto);
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdto),'iBizBusinessCentral-Account-Save')")
    @ApiOperation(value = "保存客户", tags = {"客户" },  notes = "保存客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/save")
    public ResponseEntity<Boolean> save(@RequestBody AccountDTO accountdto) {
        return ResponseEntity.status(HttpStatus.OK).body(accountService.save(accountMapping.toDomain(accountdto)));
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdtos),'iBizBusinessCentral-Account-Save')")
    @ApiOperation(value = "批量保存客户", tags = {"客户" },  notes = "批量保存客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.saveBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchByParentKey-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "获取ByParentKey", tags = {"客户" } ,notes = "获取ByParentKey")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchbyparentkey")
	public ResponseEntity<List<AccountDTO>> fetchByParentKey(AccountSearchContext context) {
        Page<Account> domains = accountService.searchByParentKey(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchByParentKey-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "查询ByParentKey", tags = {"客户" } ,notes = "查询ByParentKey")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchbyparentkey")
	public ResponseEntity<Page<AccountDTO>> searchByParentKey(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchByParentKey(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"客户" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchdefault")
	public ResponseEntity<List<AccountDTO>> fetchDefault(AccountSearchContext context) {
        Page<Account> domains = accountService.searchDefault(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"客户" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchdefault")
	public ResponseEntity<Page<AccountDTO>> searchDefault(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchRoot-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "获取Root", tags = {"客户" } ,notes = "获取Root")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchroot")
	public ResponseEntity<List<AccountDTO>> fetchRoot(AccountSearchContext context) {
        Page<Account> domains = accountService.searchRoot(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchRoot-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "查询Root", tags = {"客户" } ,notes = "查询Root")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchroot")
	public ResponseEntity<Page<AccountDTO>> searchRoot(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchRoot(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "获取停用客户", tags = {"客户" } ,notes = "获取停用客户")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchstop")
	public ResponseEntity<List<AccountDTO>> fetchStop(AccountSearchContext context) {
        Page<Account> domains = accountService.searchStop(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "查询停用客户", tags = {"客户" } ,notes = "查询停用客户")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchstop")
	public ResponseEntity<Page<AccountDTO>> searchStop(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchStop(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchUsable-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "获取可用客户", tags = {"客户" } ,notes = "获取可用客户")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchusable")
	public ResponseEntity<List<AccountDTO>> fetchUsable(AccountSearchContext context) {
        Page<Account> domains = accountService.searchUsable(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-searchUsable-all') and hasPermission(#context,'iBizBusinessCentral-Account-Get')")
	@ApiOperation(value = "查询可用客户", tags = {"客户" } ,notes = "查询可用客户")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchusable")
	public ResponseEntity<Page<AccountDTO>> searchUsable(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchUsable(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

